//
//  M4LimitManager.swift
//  M4
//
//  Created by YuChuang on 2024/8/8.
//

import Foundation
import Contacts
import CoreLocation
import UIKit
import AVFoundation
import AdjustSdk


class M4LimitVerification: NSObject {
    
    func M4RequestForTrackingAuthorization(_ needAlert: Bool = false, complete: @escaping (Bool, Bool) -> Void) {
        Adjust.requestAppTrackingAuthorization { status in
            let auth: Bool = false
            let isCancel: Bool = status == 3 ? true : false
            DispatchQueue.main.async {
                (UIApplication.shared.delegate as! AppDelegate).M4SetAdjust()
                complete(auth, isCancel)
            }
            
        }
    }
    
    
//    func M4OpenContacts(_ needAlert: Bool = false, complete: @escaping (Bool, Bool) -> Void) {
//        if M4UserDataManager.m4UserShare.M4AuditAccount == 1 {
//            complete(true, false)
//            return
//        }
//        var auth: Bool = false
//        var isCancel: Bool = false
//        let authStatus = CNContactStore.authorizationStatus(for: .contacts)
//        if authStatus == CNAuthorizationStatus.restricted || authStatus == CNAuthorizationStatus.denied {
//            auth = false
//            M4UserDataManager.m4UserShare.M4ContactData = []
//            complete(auth, isCancel)
//        }
//        else if authStatus == CNAuthorizationStatus.notDetermined {
//            CNContactStore().requestAccess(for: .contacts) { isSuccess, error in
//                if isSuccess {
//                    auth = true
//                    self.M4AllContacts()
//                }
//                
//                complete(auth, isCancel)
//            }
//        }
//        else {
//            auth = true
//            self.M4AllContacts()
//            complete(auth, isCancel)
//        }
//        
////        if needAlert && !auth {
////            self.M4_showAskAlert(icon: "icon_limit_call", name: "Libreta de direcciones", complete: { cancel in
////                isCancel = cancel
////                complete(auth, isCancel)
////            })
////        }
////        else {
////            complete(auth, isCancel)
////        }
//    }
//    
//    func M4AllContacts() {
//        if M4UserDataManager.m4UserShare.M4AuditAccount == 1 {
//            M4UserDataManager.m4UserShare.M4ContactData = []
//            return
//        }
//        var contacts: [[String:String]] = []
//        let M4Keys = [CNContactFamilyNameKey, CNContactMiddleNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey, CNContactDatesKey]
//        let M4Fetch = CNContactFetchRequest(keysToFetch: M4Keys as [CNKeyDescriptor])
//        DispatchQueue.global().async {
//            do {
//                try CNContactStore().enumerateContacts(with: M4Fetch, usingBlock: { (contact, stop) in
//                    var dic: [String:String] = [:]
//                    dic["QTsMy"] = contact.familyName
//                    dic["TFxq"] = contact.middleName
//                    dic["XoQ"] = contact.givenName
//                    for number in contact.phoneNumbers {
//                        let a = number.value as CNPhoneNumber
//                        if a.stringValue.count != 0 {
//                            dic["Yvwx"] = a.stringValue
//                        }
//                    }
//                    contacts.append(dic)
//                    M4UserDataManager.m4UserShare.M4ContactData = contacts
//                })
//            } catch {
//                print("error: \(error)")
//            }
//        }
//    }
    
    
//    func M4OpenLocation(_ needAlert: Bool = false, complete: @escaping (Bool, Bool) -> Void) {
//        var auth: Bool = false
//        var isCancel: Bool = false
//        let location: CLLocationManager = CLLocationManager()
//        location.delegate = self
//        location.desiredAccuracy = kCLLocationAccuracyBest
//        location.distanceFilter = 200
//        if CLLocationManager.authorizationStatus() == .restricted || CLLocationManager.authorizationStatus() == .denied {
//            auth = false
//        }
//        else if CLLocationManager.authorizationStatus() == .notDetermined {
//            location.requestWhenInUseAuthorization()
//            auth = true
//        }
//        else {
//            auth = true
//            location.startUpdatingLocation()
//        }
//        complete(auth, isCancel)
////        if needAlert && !auth {
////            self.M4_showAskAlert(icon: "icon_limit_location", name: "Posicionamiento", complete: { cancel in
////                isCancel = cancel
////                complete(auth, isCancel)
////            })
////        }
////        else {
////            complete(auth, isCancel)
////        }
//    }
//    
//    @objc func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//        let location = locations.last
//        let longitude = location?.coordinate.longitude as? Double ?? 0.0
//        let latitude = location?.coordinate.latitude as? Double ?? 0.0
//        M4UserDataManager.m4UserShare.M4Latitude = "\(latitude)"
//        M4UserDataManager.m4UserShare.M4Longtitude = "\(longitude)"
//        manager.stopUpdatingLocation()
//    }
    
    
    func M4OpenCameraLimit(complete: @escaping (Bool) -> Void) {
        let authStatus = AVCaptureDevice.authorizationStatus(for: AVMediaType.video)
        if authStatus == AVAuthorizationStatus.notDetermined {
            AVCaptureDevice.requestAccess(for: .video) { granted in
                complete(granted)
            }
        } else if authStatus == AVAuthorizationStatus.restricted || authStatus == AVAuthorizationStatus.denied {
            complete(false)
        } else {
            complete(true)
        }
    }
    
    //M4LimitAlertView
    func M4_showAskAlert(arr: [[String : String]], complete: @escaping (Bool) -> Void) {
        DispatchQueue.main.async {
            let alert = UINib(nibName: "M4LimitAlertView", bundle: nil).instantiate(withOwner: self).last as! M4LimitAlertView
            alert.M4LimitAlertViewUpdate(nameArray: arr)
            alert.M4LimitAlertCenterY.constant = 0
            alert.M4LimitCloseButton.isHidden = true
            alert.M4LimitCloseBlock = {
                complete(true)
            }
            alert.M4AlertViewShow()
        }
    }
    
//    func M4_showAskAlert(title: String, detail: String = "", setting: String = "Configuración", complete: @escaping (Bool) -> Void) {
//        DispatchQueue.main.async {
////            let currentVC = M4BaseViewController.M4CurrentVC()
//            let alert = UINib(nibName: "M4PublicAlertView", bundle: nil).instantiate(withOwner: self).last as! M4PublicAlertView
//            alert.m4updateAlertUI(title: title, firstText: "Ir a la configuración", secondText: "Cancelar")
//            alert.M4AlertFirstBlock = {
//                UIApplication.shared.open(NSURL(string: UIApplication.openSettingsURLString)! as URL)
//            }
//            alert.M4AlertSecondBlock = {
//                complete(true)
//            }
//            alert.M4AlertViewShow()
//            let alertController = UIAlertController(title: title, message: detail, preferredStyle: .alert)
//            let settingsAction = UIAlertAction(title: setting, style: .default) { (_) -> Void in
//                guard let settingsUrl = URL(string: UIApplication.openSettingsURLString) else {
//                    currentVC?.tabBarController?.selectedIndex = 0
//                    currentVC?.navigationController?.popToRootViewController(animated: true)
//                    return
//                }
//                
//                if UIApplication.shared.canOpenURL(settingsUrl) {
//                    UIApplication.shared.open(settingsUrl, completionHandler: { (success) in
//                        print("settingOpen: \(success)")
//                    })
//                }
//                currentVC?.tabBarController?.selectedIndex = 0
//                currentVC?.navigationController?.popToRootViewController(animated: true)
//            }
//            alertController.addAction(settingsAction)
//            currentVC?.present(alertController, animated: true, completion: nil)
//        }
//    }
    
    func M4LimitRequest(complete: @escaping () -> Void) {
        M4LocationVerification.getLocation()
        M4LimitVerification().M4RequestForTrackingAuthorization { _, _ in
                M4LocationVerification.M4OpenLocation { _, _ in
                    M4LimitVerification().M4OpenCameraLimit { _ in
                        complete()
                    }
                }
        }
//        M4LimitVerification().M4RequestForTrackingAuthorization { _, _ in
//            M4LimitVerification().M4OpenContacts { _, _ in
//                M4LocationVerification.M4OpenLocation { _, _ in
//                    M4LimitVerification().M4OpenCameraLimit { _ in
//                        complete()
//                    }
//                }
//            }
//        }
    }
    
//    func M4LimitDataAsk(complete: @escaping (Int) -> Void) {
//        M4LocationVerification.getLocation()
//        var cancelCount = 0
//        M4LimitVerification().M4RequestForTrackingAuthorization(true) { _, trackcancel in
//            cancelCount += trackcancel ? 1 : 0
//            M4LimitVerification().M4OpenContacts(true) { _, contactcancel in
//                cancelCount += contactcancel ? 1 : 0
//                M4LocationVerification.M4OpenLocation(true) { _, locationcancel in
//                    cancelCount += locationcancel ? 1 : 0
//                    complete(cancelCount)
//                }
//            }
//        }
//    }
    
    func M4LimitDataAsk1(complete: @escaping ([[String : String]]) -> Void) {
        M4LocationVerification.getLocation()
        var countArray: [[String : String]] = []
//        M4LimitVerification().M4RequestForTrackingAuthorization(true) { auth, _ in
//            if !auth {
//                let dic = ["img": "icon_limit_idfa", "name": "IDFA"]
//                countArray.append(dic)
//            }
//            M4LimitVerification().M4OpenContacts(true) { auth, _ in
//                if !auth {
//                    let dic = ["img": "icon_limit_call", "name": "Libreta de direcciones"]
//                    countArray.append(dic)
//                }
//                M4LocationVerification.M4OpenLocation(true) { auth, _ in
//                    if !auth {
//                        let dic = ["img": "icon_limit_location", "name": "Posicionamiento"]
//                        countArray.append(dic)
//                    }
//                    complete(countArray)
//                }
//            }
//        }
        
//        M4LimitVerification().M4RequestForTrackingAuthorization(true) { auth, _ in
//            if !auth {
//                let dic = ["img": "icon_limit_idfa", "name": "IDFA"]
//                countArray.append(dic)
//            }
//            
            M4LocationVerification.M4OpenLocation(true) { auth, _ in
                if !auth {
                    let dic = ["img": "icon_limit_location", "name": "Posicionamiento"]
                    countArray.append(dic)
                }
                complete(countArray)
            }
//        }
    }
    
}


class M4LocationVerification: NSObject, CLLocationManagerDelegate {
    static let shared = M4LocationVerification()
    let location = CLLocationManager()
    var locationHasUpdated = false
    var openLocationComplete: (Bool, Bool) -> Void = {_, _ in}
    
   class func M4OpenLocation(_ needAlert: Bool = false, complete: @escaping (Bool, Bool) -> Void) {
        var auth: Bool = false
        var isCancel: Bool = false
        M4LocationVerification.shared.location.delegate = M4LocationVerification.shared
        M4LocationVerification.shared.location.desiredAccuracy = kCLLocationAccuracyBest
        M4LocationVerification.shared.location.distanceFilter = kCLDistanceFilterNone
        if CLLocationManager.authorizationStatus() == .restricted || CLLocationManager.authorizationStatus() == .denied {
            auth = false
            complete(auth, isCancel)
        }
        else if CLLocationManager.authorizationStatus() == .notDetermined {
            M4LocationVerification.shared.location.requestWhenInUseAuthorization()
            auth = true
            complete(auth, isCancel)
        }
        else {
            auth = true
            complete(auth, isCancel)
        }
        
//        if needAlert && !auth {
//            self.M4_showAskAlert(icon: "icon_limit_location", name: "Posicionamiento", complete: { cancel in
//                isCancel = cancel
//                complete(auth, isCancel)
//            })
//        }
//        else {
//            complete(authr, isCancel)
//        }
    }
    
//    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
//        if CLLocationManager.authorizationStatus() == .authorizedAlways ||
//            CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
//            manager.startUpdatingLocation()
//        }
//    }
    
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        if locationHasUpdated == true { return }
        locationHasUpdated = true
        manager.stopUpdatingLocation()
        let location = locations.last
        let longitude = location?.coordinate.longitude as? Double ?? 0.0
        let latitude = location?.coordinate.latitude as? Double ?? 0.0
        print("定位信息: \(longitude)\n\(latitude)")
        M4UserDataManager.m4UserShare.M4Latitude = "\(latitude)"
        M4UserDataManager.m4UserShare.M4Longtitude = "\(longitude)"
        M4LocationVerification.shared.openLocationComplete(true, false)
        M4LocationVerification.shared.openLocationComplete = {_, _ in}
    }
    
    class func getLocation() {
        if CLLocationManager.authorizationStatus() == .authorizedAlways ||
            CLLocationManager.authorizationStatus() == .authorizedWhenInUse {
            M4LocationVerification.shared.locationHasUpdated = false
            M4LocationVerification.shared.location.startUpdatingLocation()
            print("开始获取定位信息")
        }
    }
    
    func locationManager(_ manager: CLLocationManager, didFailWithError error: any Error) {
        print(error)
    }
}
